package mail;

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 * Erzeugt Authentifizierung für Anmeldung am smtp Server
 * 
 * @author Michi
 * 
 */
public class MailAuthenticator extends Authenticator {
	private JDialog passwordDialog = new JDialog(new JFrame(), true);
	private JLabel mainLabel = new JLabel(
			"Bitte Benutzernamen und Passwort eingeben: ");
	private JLabel userLabel = new JLabel("Benutzernamen: ");
	private JLabel passwordLabel = new JLabel("Passwort: ");
	private JTextField usernameField = new JTextField(20);
	private JPasswordField passwordField = new JPasswordField(20);
	private JButton okButton = new JButton("OK");

	/**
	 * Konstruktor
	 */
	public MailAuthenticator() {
		this("");
	}

	/**
	 * Konstruktor
	 * 
	 * @param username
	 *            Email
	 */
	public MailAuthenticator(String username) {
		Container pane = passwordDialog.getContentPane();
		pane.setLayout(new GridLayout(4, 1));
		pane.add(mainLabel);
		JPanel p2 = new JPanel();
		p2.add(userLabel);
		p2.add(usernameField);
		usernameField.setText(username);
		pane.add(p2);
		JPanel p3 = new JPanel();
		p3.add(passwordLabel);
		p3.add(passwordField);
		pane.add(p3);
		JPanel p4 = new JPanel();
		p4.add(okButton);
		pane.add(p4);
		passwordDialog.pack();
		ActionListener al = new HideDialog();
		okButton.addActionListener(al);
		usernameField.addActionListener(al);
		passwordField.addActionListener(al);
	}

	/**
	 * Dialog zur Passworteingabe
	 * 
	 * @author Michi
	 * 
	 */
	class HideDialog implements ActionListener {
		@SuppressWarnings("deprecation")
		public void actionPerformed(ActionEvent e) {
			passwordDialog.hide();
		}
	}

	/**
	 * Erzeugt Authtifizierung
	 */
	@SuppressWarnings("deprecation")
	public PasswordAuthentication getPasswordAuthentication() {
		passwordDialog.show();
		// getPassword() liefert ein Array, aus Sicherheitsgründen
		// Dieses muss in eine Zeichenkette umgewandelt werden.
		// PasswordAuthentication() constructor.
		String password = new String(passwordField.getPassword());
		String username = usernameField.getText();
		// Löschen des PWD
		// Der Provider kennt das PWD noch
		passwordField.setText("");
		return new PasswordAuthentication(username, password);
	}
}